﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Linq;
using MathematicallySafe.HeadCounter.Data;
using MathematicallySafe.HeadCounter.Data.Common;

namespace MathematicallySafe.HeadCounter.Services.Exporters
{
    public class HtmlPageGenerator
    {
        private readonly PageController _pages = new PageController();
        private readonly string _guildName;

        public HtmlPageGenerator(string guildName, PageController pages)
        {
            _pages = pages;
            _guildName = guildName;
        }

        public void CreatePage(Page page)
        {
            var tabContainer = HtmlSnippetHelper.ContentContainer(24, _pages.GenerateTabSection(page.Name));
            var contentContainer = HtmlSnippetHelper.ContentContainer(24, page.Generator());

            var injectableContent = new Dictionary<string, string>
                                    {
                                        {"{title}", page.Name},
                                        {"{guild}", _guildName},
                                        {"{tabs}", tabContainer.ToString()},
                                        {"{content}", contentContainer.ToString()},
                                        {"{footer}", MakeWebPageFooter().ToString()}
                                    };

            MakePageFromInjectableContent(page.Filename, injectableContent);
        }

        private void MakePageFromInjectableContent(string filename, Dictionary<string, string> injectableContent)
        {
            string qfn = Constants.HtmlDirectory + filename;

            if (File.Exists(qfn)) File.Delete(qfn);

            using (TextWriter output = File.CreateText(qfn))
            using (TextReader input = File.OpenText("default.html"))
            {
                string line;
                while ((line = input.ReadLine()) != null)
                {
                    injectableContent.ForEach(c => line = Inject(line, c.Key, c.Value));
                    output.WriteLine(line);
                }
            }
        }

        private string Inject(string line, string marker, string content)
        {
            if (line.Contains(marker))
            {
                line = line.Replace(marker, content);
            }

            return line;
        }

        private XElement MakeWebPageFooter()
        {
            DateTime now = DateTime.Now;

            return HtmlSnippetHelper.CenteredContentContainer(12,
                                                               new XElement("tt", new XAttribute("class", "small"),
                                                                            now.ToLongDateString() + " " +
                                                                            now.ToUniversalTime().ToShortTimeString() + " UTC"));
        }
    }
}